/*
 * tstring.c
 *
 *  Created on: Jan 10, 2016
 *      Author: root
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "tstring.h"
#include "../basic/operator.h"

/* allocate name to string area */
static char *store_string(int len, const char *str, char fill) {
	char *buf = (char*) malloc(len + 1);
	if (str != 0) {
		snprintf(buf, len + 1, "%s", str);
	} else {
		memset(buf, fill, len);
		buf[len] = 0;
	}
	return buf;
}

Cell* make_string_n(Scheme *sc, const char *str, int len) {
	Cell* x = make_cell(sc, G_NIL, G_NIL);
	// (x)->_flag = T_ATOM;
	(x)->_type = STRING_TYPE;
	(x)->_string = store_string(len, str, 0);
	return (x);
}

// 创建字符串
Cell* make_string(Scheme *sc, const char *str) {
	return make_string_n(sc, str, strlen(str));
}

// 创建空字符串
Cell* make_empty_string(Scheme *sc, int len, char fill) {
	Cell* x = make_cell(sc, G_NIL, G_NIL);
	// (x)->_flag = T_ATOM;
	(x)->_type = STRING_TYPE;
	(x)->_string = store_string(len, 0, fill);
	return (x);
}



// (make-string n)
// (make-string n c)
Cell* op_make_string(Scheme *sc) {
	LOG_INPUT(sc, "atoms/tstring", "op_make_string");

	int len = first(sc->args)->_longValue;
	int fill = ' ';
	if (rest(sc->args) != G_NIL) {
		fill = (int)(second(sc->args)->_longValue);
	}
	sc->returnValue = make_empty_string(sc, len, (char) fill);

	LOG_OUTPUT(sc, "atoms/tstring", "op_make_string");
	return pop_callstack(sc);
}

void init_string_operators(Scheme *sc) {
	ADD_OPERATOR(sc, "make-string", make_string);
}

//TODO following
//my_g_hash_table_insert(table, "string->symbol", op_str2sym);
//my_g_hash_table_insert(table, "string->atom", op_str2atom);
//my_g_hash_table_insert(table, "symbol->string", op_sym2str);
//my_g_hash_table_insert(table, "atom->string", op_atom2str);

/*
  test_op(sc, "(string->symbol \"abc\")", "abc");
  test_op(sc, "(string->atom \"3\")", "3");
  test_op(sc, "(string->atom \"101\" 2)", "5");
 * */